package items;

import java.awt.Point;

import main.Map;

import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Input;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.geom.Polygon;

import shared.BlockTypeList;
import shared.Grid;
import shared.MouseInput;

import entities.Player;

public class ItemBlock extends Item {
	private String blockType;
	
	public ItemBlock(int id, int x, int y, int w, int h, String type) throws SlickException {
		super(id, x, y, w, h);
		setType("block");
		this.blockType = type;
		setTexture(BlockTypeList.getBlockItemResourcePath(type));
	}
	
	@Override
	public void use(GameContainer gc, Player player) {
		if(gc.getInput().isMouseButtonDown(Input.MOUSE_LEFT_BUTTON)) {
			int midX = player.getX() + player.getWidth()/2;
			int midY = player.getY() + player.getHeight()/2;
			int x = MouseInput.getMousePosX();
			int y = MouseInput.getMousePosY();
			
			Point topLeft = Grid.calculateGridPosition(midX, midY);
			topLeft.setLocation(topLeft.getX()-Grid.getSize(), topLeft.getY()-2*Grid.getSize());
			int width = 3 * Grid.getSize();
			int height = 4 * Grid.getSize();
			
			Polygon poly = new Polygon(new float[] {(float) topLeft.getX(), (float) topLeft.getY(),
													(float) (topLeft.getX() + width), (float) topLeft.getY(),
													(float) (topLeft.getX() + width), (float) (topLeft.getY() + height),
													(float) topLeft.getX(), (float) (topLeft.getY() + height)});
			
			/* Field the player place blocks/
			 * xxx 1
			 * xxx 2
			 * xpx 3
			 * xxx 4
			 */
			if(poly.contains(x, y)) {
				Point playerPos = Grid.calculateGridPosition(midX, midY);
				Point mousePos = Grid.calculateGridPosition(x, y);
				if(Map.getBlock(x, y) == null && blockType != null && (playerPos.getX() != mousePos.getX() || playerPos.getY() != mousePos.getY())) {
					try {
						Map.addBlock(x,y, blockType);
						setCount(getCount() - 1);
					} catch (SlickException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}

	public String getBlockType() {
		return blockType;
	}

	public void setBlockType(String type) {
		this.blockType = type;
	}
}
